package cn.swu.lyx.homework4

import android.util.Log
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException

class Connection {
    var conn: Connection? = null
    companion object {
        private const val TAG = "mysql"
        fun mymysql() {
            val thread = Thread(Runnable {
                while (!Thread.interrupted()) {
                    try {
                         Thread.sleep(100) // 每隔0.1秒尝试连接
                    } catch (e: InterruptedException) {
                        Log.e(TAG, e.toString())
                    }

                    // 1.加载JDBC驱动
                    try {
                        Class.forName("com.mysql.jdbc.Driver")
                        Log.v(TAG, "加载JDBC驱动成功")
                    } catch (e: ClassNotFoundException) {
                        Log.e(TAG, "加载JDBC驱动失败")
                        return@Runnable
                    }

                    // 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
                    val ip = "10.100.250.206"
                    val port = 3306
                    val dbName = "AndroidTask"
                    val url = ("jdbc:mysql://" + ip + ":" + port
                            + "/" + dbName + "?useUnicode=true&characterEncoding=utf-8&useSSL=false")
                    // 构建连接mysql的字符串
                    val user = "root"
                    val password = "010620"

                    // 3.连接JDBC
                    try {
                        val conn: Connection = DriverManager.getConnection(url, user, password)
                        Log.d(TAG, "数据库连接成功")
                        conn.close()
                        return@Runnable
                    } catch (e: SQLException) {
                        e.message?.let { Log.e(TAG, it) }
                    }
                }
            })
            thread.start()
        }
    }
}